extends CharacterBody2D
class_name Loot


@onready var collision = $CollisionShape2D
var jumpSpeedY = -100
var jumpSpeedYRandomRange = 50
var jumpSpeedX = 60
var jumpSpeedXRandomRange = 30
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var gravityScale = 0.5
var airResistence = 100

var playerEntered = false
var itemResName


func _ready():
	#init(ImageTexture.create_from_image(Global.imageFileDict["ironRod"]), Vector2(100, 100))
	pass
	

func init(itemResName, position):
	self.itemResName = itemResName
	
	var s = $Sprite2D as Sprite2D
	s.texture = ImageTexture.create_from_image(Global.imageFileDict[itemResName])
	
	var width = s.texture.get_width()
	var height = s.texture.get_height()
	
	s.offset.x = 0
	s.offset.y = -height / 2
	
	s.position.x = 0
	s.position.y = 0
	
	var interectCollisionShape = $Interect/CollisionShape2D as CollisionShape2D
	var interectRectangleShape = interectCollisionShape.shape as RectangleShape2D
	interectRectangleShape.size.x = width
	interectRectangleShape.size.y = height
	interectCollisionShape.position.x = 0
	interectCollisionShape.position.y = -height / 2
	
	var bodyCollisionShape = collision.shape as RectangleShape2D
	bodyCollisionShape.size.x = width
	bodyCollisionShape.size.y = height
	collision.position.x = 0
	collision.position.y = -height / 2
	
	global_position = position
	
	velocity.x = ( jumpSpeedX if randf() < 0.5 else -jumpSpeedX ) + (randf() * 2 - 1.0) * jumpSpeedXRandomRange
	velocity.y = jumpSpeedY + (randf() * 2 - 1.0) * jumpSpeedYRandomRange
	
	
func _physics_process(delta):
	if not is_on_floor():
		velocity.y += gravity * gravityScale * delta	
	
	velocity.x = move_toward(velocity.x, 0, airResistence * delta)
	
	move_and_slide()
	
	if Input.is_action_just_pressed("Interect") and playerEntered:
		pickupItem()


func _on_interect_body_entered(body):
	if body.is_in_group("Player"):
		playerEntered = true


func _on_interect_body_exited(body):
	if body.is_in_group("Player"):
		playerEntered = false
		

func pickupItem():
	var player = Global.playerInstance as PlayerScript
	var toWeapon = GlobalUtils.strFirstChar2Upper(itemResName)
	player.changeWeapon(toWeapon)
	queue_free()
